//
//  ViewController.m
//  SegmentDownloadDemo
//
//  Created by gao on 2018/5/29.
//  Copyright © 2018年 gao. All rights reserved.
//

#import "ViewController.h"
#import "SegmentDownload.h"
#import "SegmentDownloadSession.h"
#import "YYFPSLabel.h"
#import "SegmentDownloadProtocol.h"

@interface DownloadCell:UITableViewCell<SegmentDownloadProtocol>
{
    IBOutlet UILabel *nameLabel;
    IBOutlet UILabel *statelabel;
    IBOutlet UILabel *speedLabel;
    IBOutlet UILabel *sizelabel;
    IBOutlet UIProgressView *progressView;
    
    
}
@property(nonatomic,strong)NSDictionary*cellInfo;
@end

@implementation DownloadCell

-(void)setCellInfo:(NSDictionary *)cellInfo{
    _cellInfo = cellInfo;
    if (_cellInfo) {
        SegmentDownloadTask *task = [self getDownloadTask];
        if (task) {
            [self updateDownloadTaskDownloadSize:task.downloadBytes totalSize:task.fileTotalBytes];
            [self updateDownloadTaskProgress:task.progress];
            [self updateDownloadTaskState:task.status];
            //        [self updateDownloadTaskSpeed:task]
        }
        else{
            sizelabel.text = @"";
            progressView.progress = 0;
            statelabel.text = @"未下载";
            
        }
        speedLabel.text = @"";
        nameLabel.text = [cellInfo[@"path"]lastPathComponent];

    }
}

#pragma mark -- SegmentDownloadProtocol
-(SegmentDownloadTask *)getDownloadTask{
    NSString *path = self.cellInfo[@"path"];
    NSString *urlStr = [NSString stringWithFormat:@"http://static0.e360app.cn%@",[path substringFromIndex:1]];
    NSURL *downloadURL = [NSURL URLWithString:urlStr];
    return [SegmentDownload getDownloadTaskWithURL:downloadURL];
}
-(void)updateDownloadTaskSpeed:(NSString*)speed{
    speedLabel.text = speed;
}
-(void)updateDownloadTaskState:(DownloadTaskStatus)status{
    switch (status) {
        case kDownloadTaskStatusNone:
            statelabel.text = @"初始化状态";
            break;
        case kDownloadTaskStatusWaiting:
            statelabel.text = @"等待下载";
            break;
        case kDownloadTaskStatusDownloading:
            statelabel.text = @"下载中";
            break;
        case kDownloadTaskStatusStart:
            statelabel.text = @"开始下载";
            break;
        case kDownloadTaskStatusFailed:
            statelabel.text = @"下载失败";
            break;
        case kDownloadTaskStatusFinished:
            statelabel.text = @"下载完成";
            break;
        case kDownloadTaskStatusSuspended:
            statelabel.text = @"下载暂停";
            break;
        default:
            break;
    }
}
-(void)updateDownloadTaskProgress:(float)progress{
    progressView.progress = progress;
}
-(void)updateDownloadTaskDownloadSize:(NSInteger)downloadedSize totalSize:(NSInteger)totalSize{
    NSString *downloadedStr = [NSByteCountFormatter stringFromByteCount:downloadedSize countStyle:NSByteCountFormatterCountStyleFile];
    NSString *totalSizeStr = [NSByteCountFormatter stringFromByteCount:totalSize countStyle:NSByteCountFormatterCountStyleFile];
    sizelabel.text = [NSString stringWithFormat:@"%@/%@",downloadedStr,totalSizeStr];
}
@end

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>{
    IBOutlet UITableView *table;
}
@property(nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [SegmentDownload configMaxConcurrent:5];
    [SegmentDownload startDownload];
    [SegmentDownload setMessageReceiverContainer:table];
    YYFPSLabel *label = [YYFPSLabel new];
    [label sizeToFit];
    [self.view addSubview:label];
    label.frame = CGRectMake(0, 60, 100, 50);

    NSString *dataPath = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:dataPath];
    self.dataArray = [NSMutableArray new];
    NSArray *list = dic[@"list"];
    for (NSDictionary *dict in list) {
        NSArray *items = dict[@"items"];
        NSString *name = dict[@"name"];
        NSMutableArray *arr = @[].mutableCopy;
        for (NSDictionary * temp in items) {
            NSArray *subItem = temp[@"items"];
            for (NSDictionary *downloadInfo in subItem) {
                [arr addObject:downloadInfo];
            }
        }
        [self.dataArray addObject:@{@"name":name,@"items":arr}];
    }

    NSLog(@"%@",self.dataArray);
    
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)updateSpeed{
    NSLog(@"QQQ");
}
-(IBAction)clickClean:(id)sender{
    [SegmentDownload clean];
    
}
-(IBAction)clickStart:(id)sender{

//
//    task = [SegmentDownload addDownloadTaskWithURL:[NSURL URLWithString:@"http://static0.e360app.cn/data/update_files/1/zip/version_20170209132424/product_file_2.zip"] totalBytes:95944876];
//    [SegmentDownload prepareDownloading:task];
    
    
    
    
    [SegmentDownload startDownload];
}
-(IBAction)clickAddTask:(id)sender{
    [SegmentDownload clean];

    for (int i = 0; i < self.dataArray.count; i++) {
        NSDictionary *dic = self.dataArray[i];
        NSArray *array = dic[@"items"];
        for (NSDictionary *subDic in array) {
            NSString *path = subDic[@"path"];

            NSInteger size = [subDic[@"size"]integerValue];
            NSString *urlStr = [NSString stringWithFormat:@"http://static0.e360app.cn%@",[path substringFromIndex:1]];
            NSURL *downloadURL = [NSURL URLWithString:urlStr];
            SegmentDownloadTask *task = [SegmentDownload addDownloadTaskWithURL:downloadURL totalBytes:size];
             [SegmentDownload prepareDownloading:task];
        }
    }
    [table reloadData];
    
//    [SegmentDownload startDownload];
}
-(IBAction)crash:(id)sender{
//    [SegmentDownloadSession reCreateSession];
    NSArray *a = @[];
    a[2];
}
-(IBAction)clickReSession:(id)sender{
    [SegmentDownloadSession reCreateSession];
//    NSURLSession *session = [SegmentDownloadSession session];
//    [session getTasksWithCompletionHandler:^(NSArray<NSURLSessionDataTask *> * _Nonnull dataTasks, NSArray<NSURLSessionUploadTask *> * _Nonnull uploadTasks, NSArray<NSURLSessionDownloadTask *> * _Nonnull downloadTasks) {
//        [downloadTasks enumerateObjectsUsingBlock:^(NSURLSessionDownloadTask * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//           NSLog(@"task state %ld",obj.state);
//        }];
//    }];
//    NSMutableDictionary *dictM = [session valueForKey:@"tasks"];
//    [dictM enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSURLSessionDownloadTask *obj, BOOL * _Nonnull stop) {
//        NSLog(@"task state %ld",obj.state);
//
////        [SegmentDownload queryTaskWithTaskDescription:obj.taskDescription completion:^(SegmentDownloadTask *task, SegmentDownloader *downloader, SegmentDownloadTask_SubTask *subTask, NSInteger subTaskIndex) {
////
////            NSLog(@"")
////        }];
//
//    }];
}
#pragma mark -- UITableViewDelegate DataSource
- (void)setExtraCellLineHidden: (UITableView *)tableView
{

    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray[section][@"items"]count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}





-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"downloadCell"];
    cell.cellInfo = self.dataArray[indexPath.section][@"items"][indexPath.row];
    [SegmentDownload addMessageReceiver:cell];
    return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return self.dataArray[section][@"name"];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


@end
